package com.jshop.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jshop.service.JSHOP_USER_DAO;

@WebFilter("/backstage/*")
public class Admin implements Filter {

    public Admin() {
    }

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hsrequest = (HttpServletRequest)request;
		HttpServletResponse hsresponse = (HttpServletResponse)response;
		
		hsrequest.setCharacterEncoding("UTF-8");
//		hsresponse.setCharacterEncoding("UTF-8");
//		hsresponse.setContentType("text/html;charset=utf-8");
		

		HttpSession session = hsrequest.getSession();
//				String isadminlogin = hsrequest.getParameter("isadminlogin");
		String isadminlogin = (String)session.getAttribute("isadminlogin");
		
		
		String re_uri = hsrequest.getRequestURI();
		String cpath = hsrequest.getContextPath();
		String uri = re_uri.substring(cpath.length());
		if(uri.contains("admin_")) {
			if (isadminlogin !=null && isadminlogin.equals("1")) {
				chain.doFilter(hsrequest, hsresponse);
			}else {
				PrintWriter out = response.getWriter();
				out.write("<script>");
				out.write("alert('please log in first!');");
				out.write("location.href='login.jsp';");
				out.write("</script>");
				out.close();
				return;
			}
		}else {
			chain.doFilter(hsrequest, hsresponse);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
